#!/bin/bash
# This script will make sure that the preview and srcltx LaTeX packages are 
# installed (and install them if they are not.

date > /tmp/lyx-install.log

# Locate TeX binaries.

LOCALDIR=/usr/local/teTeX/share/texmf.local
for TEXBIN in /usr/local/teTeX/bin/powerpc-apple-darwin-current /sw/bin /usr/local/bin /opt/local/teTeX/bin ''
do
  [ -x "$TEXBIN"/kpsewhich ] && break
done
[ "$TEXBIN" ] || { echo 'Cannot find teTeX installation.' >> /tmp/lyx-install.log; exit 1; }

echo "Found TeXbin directory: $TEXBIN" >> /tmp/lyx-install.log


# Locate where to install new TeX packages.

[ -d "$LOCALDIR" ] || { LOCALDIR=/sw/etc/texmf.local; [ -d "$LOCALDIR" ]; } || { LOCALDIR=/opt/local/share/texmf-local; [ -d "$LOCALDIR" ];} || { echo 'Cannot find texmf.local directory.' >> /tmp/lyx-install.log; exit 1; }

echo "Found installation directory: $LOCALDIR" >> /tmp/lyx-install.log

cd "$LOCALDIR"


# Create tex/latex folders if necessary.

[ -d tex ] || mkdir tex
[ -d tex/latex ] || mkdir tex/latex 


# Install srcltx files, if necessary.

{ "$TEXBIN"/kpsewhich srcltx.sty && echo "srcltx already installed." >> /tmp/lyx-install.log; } || { cp -R "$1"/srcltx  tex/latex/ && echo "Installed srcltx into $LOCALDIR/tex/latex/ successfully." >> /tmp/lyx-install.log; } || { echo 'Cannot install Srcltx files.' >> /tmp/lyx-install.log; exit 1; }

# $1 is the installer directory. I need to put srcltx into that directory manually!


# Install preview files, if necessary.

{ "$TEXBIN"/kpsewhich preview.sty && echo "preview already installed." >> /tmp/lyx-install.log; } || { cp -R "$1"/preview  tex/latex/ && echo "Installed preview into $LOCALDIR/tex/latex/ successfully." >> /tmp/lyx-install.log; } || { echo 'Cannot install Preview files.' >> /tmp/lyx-install.log; exit 1; }

# Again, $1 is the installer directory. I need to put preview into that directory manually!


# Run texhash

"$TEXBIN"/texhash || { echo 'Cannot run texhash command.' >> /tmp/lyx-install.log; exit 1; }

echo "texhash run successfully." >> /tmp/lyx-install.log

echo 'Installation successful!' >> /tmp/lyx-install.log

exit 0